package books.ThinkingInJava.src.Chapter18;


import books.ThinkingInJava.src.Tools.FileKit;
import books.ThinkingInJava.src.Tools.Output;

import java.io.*;

/**
 * @author bloodcolding
 * @since 12/27/2018 8:27 PM
 */
public class BufferedPerformanceBattle {

    String s = null;

    public static void main(String[] args) throws IOException {
        BufferedPerformanceBattle bufferedPerformanceBattle = new BufferedPerformanceBattle();
        String path = FileKit.filePathTransfer("D:\\Doc\\Test\\test.txt");
        bufferedPerformanceBattle.writeData(path, bufferedPerformanceBattle.makeString(1000));
        bufferedPerformanceBattle.buffered(path);
        bufferedPerformanceBattle.noBufferd(path);

    }

    public String makeString(int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append("123456789");
        }
        return sb.toString();
    }

    public void writeData(String path, String data) throws IOException {
        PrintWriter printWriter = new PrintWriter(new File(path));
        printWriter.append(data);
        printWriter.flush();
        printWriter.close();

        RandomAccessFile randomAccessFile = new RandomAccessFile(new File(path), "rw");
        randomAccessFile.getFilePointer(); //先获取指针，再进行操作
        randomAccessFile.seek(100l);
        randomAccessFile.write((new String("Well played")).getBytes());
        randomAccessFile.seek(10l);
        randomAccessFile.write((new String("Well played")).getBytes());
        randomAccessFile.close();
    }

    public void noBufferd(String path) throws IOException {
        long begin = System.currentTimeMillis();
        FileReader fileReader = new FileReader(path);
        int i = 0;
        while ((i = fileReader.read()) != -1) {

        }
        fileReader.close();
        long end = System.currentTimeMillis();

        Output.println("No buffered:   " + (end - begin));
    }

    public void buffered(String path) throws IOException {
        long begin = System.currentTimeMillis();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {

        }
        bufferedReader.close();
        long end = System.currentTimeMillis();
        Output.println("Bufferd:    " + (end - begin));
    }
}

